# -*- encoding=utf8 -*-
__author__ = "yupf"
"""
 windows启动wda:
    1、使用sib(https://sonic-cloud.cn/sib/sib-run.html#%E5%90%AF%E5%8A%A8-webdriveragent-server): 
       sib run wda -b org.cloud.sonic.WebDriverAgentRunner --server-local-port=8101 --server-remote-port=8200
       --server-local-port : wda 本地端口
       --server-remote-port: 转发端口
    2、使用tidevice( pip 安装： https://github.com/alibaba/taobao-iphone-device):
        tidevice -u [设备 udid] wdaproxy -B [wda 的 bundle Id] --port 8100

"""
from airtest.core.api import *
import pathlib
import sys
import re
import platform


p = pathlib.Path(__file__).parents
sys.path.append(os.path.join(p[2]))
sys.path.append(os.path.join(p[1], 'passenger_detail.air'))

using(os.path.join(p[1], 'login.air'))
using(os.path.join(p[1], 'select_from_to_city.air'))
using(os.path.join(p[1], 'select_date.air'))
using(os.path.join(p[1], "adults_num.air"))
using(os.path.join(p[1], 'passenger_detail.air'))
using(os.path.join(p[1], 'new_card.air'))

from login import login
from select_from_to_city import select_from_to_city
from select_date import select_date
from adults_num import adults_num
from passenger_detail import passenger_detail
from new_card import new_card

from poco.drivers.ios import iosPoco
from poco.exceptions import PocoTargetTimeout

from easyjet_order import get_resp, push_info, say


def device_connect(host:str = "127.0.0.1", port: str = '8300'):
    if platform.system().lower() == 'windows':
        connect_device(f"http://{host}:{port}")
    elif platform.system().lower() == 'darwin':
        connect_device(f"iOS:///{host}:{port}")
    else:
        raise SystemError('暂不支持的系统类型')

def main(order_info, pnr_vo ):
    if len(order_info["passengers"]) != order_info["count"]:
        pnr_vo["status"] = 250
        pnr_vo["errorMessage"] = "订单包含儿童"
        push_info(pnr_vo)
        return

    auto_setup(__file__)

    # connect_device("iOS:///127.0.0.1:8300")
    device_connect()
    poco = iosPoco()

    # new_card(poco,card_info,mac_say)

    # 登录
    # login(poco,order_info['user'], order_info['passwd'])
    login(poco, '69e48e07c55b@creazyair.shop', 'Aa1)cj1Acz')

    # 返回首页
    print("返回首页")
    poco("Back", type="Button").click()
    # wait(Template(r"tpl1685282683309.png", record_pos=(-0.335, -0.793), resolution=(1242, 2208)))
    poco('easyJet.TabBarView').wait_for_appearance()
    # 选择出发-目的地

    select_from_to_city(poco, order_info['from_city_code'], order_info['to_city_code'])

    # 选择日期
    say(f"您好，请手动选择日期：{order_info['date']}，选择完毕后，输入yes 或者 y让脚本继续运行")
    # select_date(poco,'2023','06','9')
    while True:
        msg = input(f"pip 选择日期:{order_info['date']}完毕后，输入yes or y继续：\n")
        if msg in ['yes', 'y']:
            break

    # 选择乘客人数
    adults_num(order_info['count'])

    # 选择币种
    touch(Template(r"tpl1685407865723.png", record_pos=(0.019, 0.278), resolution=(1242, 2208)))

    wait(Template(r"tpl1685408022160.png", record_pos=(-0.002, -0.812), resolution=(1242, 2208)))

    poco('currency_selector_button').click()
    m = {
        "CHF": "Swiss Franc",
        "CSK": "Czech Koruna",
        "DKK": "Danish Krone",
        "EUR": "Euro",
        "GBP": "British Pound Sterling",
        "HUF": "Hungarian Forint",
        "MAD": "Moroccan Dirham",
        "PLN": "Polish Zloty",
        "SEK": "Swedish Krona",
        "USD": "US Dollars"
    }
    poco(m[order_info['target_currency']]).click()

    # 选择航班

    sleep(2)

    while True:
        fe = poco('ScrollView').offspring(nameMatches=f".+{order_info['flight_num']}").sibling('Other').child(
            labelMatches='^Standard.*$').exists()
        if not fe:
            swipe((0.5, 0.5), (0.5, 0.3))
        else:
            break
    poco('ScrollView').offspring(nameMatches=f".+{order_info['flight_num']}").sibling('Other').child(
        labelMatches='^Standard.*$').wait_for_appearance(5)
    poco('ScrollView').offspring(nameMatches=f".+{order_info['flight_num']}").sibling('Other').child(
        labelMatches='^Standard.*$').click()

    # 下一步

    wait(Template(r"tpl1685410401245.png", record_pos=(0.001, -0.787), resolution=(1242, 2208)))
    touch(Template(r"tpl1685410413991.png", record_pos=(0.007, 0.798), resolution=(1242, 2208)))

    # 乘客信息

    wait(Template(r"tpl1685410447780.png", record_pos=(0.003, -0.787), resolution=(1242, 2208)))

    v = poco('price_label').attr("value")
    piao_price = re.findall('\d+\.\d+', v)[0]
    pnr_vo['ticketAmount'] = float(piao_price)
    pnr_vo['depPayAmount'] = float(piao_price)

    if float(piao_price) > order_info['count'] * order_info['target_price']:
        pnr_vo['status'] = 403
        pnr_vo["webPrice"] = float(piao_price)
        push_info(pnr_vo)
        return

    # 填写乘客信息
    passenger_detail(poco, order_info['passengers'])

    # 点击继续
    # wait(Template(r"tpl1685413530255.png", record_pos=(-0.32, 0.811), resolution=(1242, 2208)))
    # poco(label="Continue", type='Button').wait_for_appearance()
    # poco(label="Continue", type='Button').click()

    # touch(Template(r"tpl1685413537378.png", record_pos=(-0.321, 0.812), resolution=(1242, 2208)))
    # seats & cars
    wait(Template(r"tpl1685634536817.png", record_pos=(0.004, -0.789), resolution=(1242, 2208)))

    swipe([0.5, 0.5], vector=(0.5, 0.3))
    poco('Skip', type='Button').wait_for_appearance()
    poco('Skip', type='Button').click()

    # 选择条款
    poco("I'm happy with my selection", type='Button').click((0.5, 0.5))

    # add cabin bags
    wait(Template(r"tpl1685634871197.png", record_pos=(0.008, -0.793), resolution=(1242, 2208)))
    poco('Skip', type='Button').wait_for_appearance()
    poco('Skip', type='Button').click()
    # add luggage

    wait(Template(r"tpl1685634925751.png", record_pos=(0.008, -0.787), resolution=(1242, 2208)))
    kg_15, kg_23 = order_info['luggage_num']
    if kg_15 != 0:
        for _ in range(kg_15):
            poco(nameMatches="15kg .*").click((0.9, 0.5))
    if kg_23 != 0:
        for _ in range(kg_23):
            poco(nameMatches="23kg .*").click((0.9, 0.5))

    v1 = poco('price_label').attr("value")
    bag_price = re.findall('\d+\.\d+', v1)[0]
    pnr_vo['depBagAmount'] = float(bag_price)

    touch(Template(r"tpl1685634936385.png", record_pos=(0.004, 0.795), resolution=(1242, 2208)))

    # contact detail

    # 选择旅行原因
    wait(Template(r"tpl1685635007374.png", record_pos=(-0.007, -0.791), resolution=(1242, 2208)))
    touch(Template(r"tpl1685635019846.png", record_pos=(-0.304, 0.051), resolution=(1242, 2208)))
    touch(Template(r"tpl1685635051276.png", record_pos=(-0.138, 0.816), resolution=(1242, 2208)))
    # checkout

    wait(Template(r"tpl1685635075289.png", record_pos=(0.004, -0.791), resolution=(1242, 2208)))
    sleep(1.5)
    swipe((0.5, 0.5), vector=(0.5, -0.1))
    swipe((0.5, 0.5), vector=(0.5, 0.4))
    sleep(1.5)
    poco('Accept terms and conditions', type="Button").click()

    # 获取最后总金额

    mt = poco('Final price').sibling("price_label").attr('value')

    final_price = re.findall('\d+\.\d+', mt)[0]

    # 支付总额
    pnr_vo['paymentVoList'][0]['settlementAmount'] = float(final_price)
    # 支付币种
    pnr_vo['paymentVoList'][0]['settlementCurrency'] = order_info['target_currency']
    # 支付行李总额，去程和回程总额
    pnr_vo['baggagePrice'] = (pnr_vo['depBagAmount'] or 0) + (pnr_vo['retBagAmount'] or 0)

    print(pnr_vo)
    # 选择 apple pay
    if float(piao_price) > order_info['count'] * order_info['target_price']:
        pnr_vo['status'] = 403
        pnr_vo["webPrice"] = float(piao_price)
        push_info(pnr_vo)

    else:
        card_e = poco(nameMatches='^Set up .*$', type='Button').exists()
        print(card_e)
        if card_e:
            print("未绑卡！")
            pnr_vo['status'] = 401
            push_info(pnr_vo)


        else:
            print("手机钱包已绑卡，进入支付页面")
            poco(nameMatches='^Buy with .*$', type='Button').click()

        # 输入密码支付
        poco('输入设备密码支付', type="Button").wait_for_appearance()
        poco('输入设备密码支付', type="Button").click()

        # 输入密码
        for _ in range(4):
            poco('0').click()
            sleep(1)

        poco('Booking Confirmation', type='NavigationBar').wait_for_appearance()
        pnr_vo['status'] = 450
        time.sleep(3)
        for _ in range(5):
            try:
                t: str = poco('booking_reference').attr('value')
                order_num = ''.join(re.split(r"\s+", t))
                pnr_vo['pnr'] = order_num
                break
            except Exception as err:
                print(err)
                time.sleep(5)
        else:
            pnr_vo['status'] = 440
            pnr_vo["errorMessage"] = "获取票号异常，手工账号核实"

        # 回调
        push_info(pnr_vo)


if __name__ == '__main__':
    while True:
        try:
            order_info, pnr_vo = get_resp()  # 获取订票人信息
            main(order_info, pnr_vo)
            stop_app("com.mttnow.iphone.easyjet")
        except Exception as err:
            print(err)
            time.sleep(5)


